package org.votes.util;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import org.votes.bean.Details;

public class DetailsOperationUtil {
	
	/**
	 * Integer detail's ID
	 */
	public static HashMap<Integer, Object[]> detailMap = new HashMap<Integer, Object[]>();
	
	public static ConcurrentHashMap<Integer, Details> datailDataMap = new ConcurrentHashMap<Integer, Details>();
	
	
	public static void addDetails(Details detail) {
		if(datailDataMap.get(detail.getId()) == null) {
			datailDataMap.put(detail.getId(), detail);
		}else {
			Details detailData = datailDataMap.get(detail.getId());
			detailData.setCount1(detailData.getCount1() + detail.getCount1());
			detailData.setCount2(detailData.getCount2() + detail.getCount2());
			detailData.setCount3(detailData.getCount3() + detail.getCount3());
			detailData.setCount4(detailData.getCount4() + detail.getCount4());
		}
	}

	/**
	 * Integer count's ID
	 * Integer count's Value
	 */
	private static Object[] initCountMap(Integer detailId) {
		ConcurrentHashMap<Integer, Integer> count1 = new ConcurrentHashMap<Integer, Integer>();
		ConcurrentHashMap<Integer, Integer> count2 = new ConcurrentHashMap<Integer, Integer>();
		ConcurrentHashMap<Integer, Integer> count3 = new ConcurrentHashMap<Integer, Integer>();
		ConcurrentHashMap<Integer, Integer> count4 = new ConcurrentHashMap<Integer, Integer>();
		count1.put(1, 0);
		count2.put(2, 0);
		count3.put(3, 0);
		count4.put(4, 0);
		Object[] obj = new Object[]{count1, count2, count3, count4};
		return obj;
	}
	
	public static boolean initDetailMap(Integer detailId) {
		Object[] obj = initCountMap(detailId);
		detailMap.put(detailId, obj);
		return true;
	}

	public static void updateCount(Integer detailId, Integer detailCountId) {
		if(detailMap.get(detailId) == null) {
			initDetailMap(detailId);
		}
		Object[] objs = detailMap.get(detailId);
		int i = 1;
		for(Object obj : objs) {
			ConcurrentHashMap<Integer, Integer> countMap = (ConcurrentHashMap<Integer, Integer>) obj;
			synchronized (countMap) {
				int countValue = countMap.get(i);
				if(i == detailCountId) {
					++countValue;
				}
				countMap.put(i, countValue);
			}
			i++;
		}
		detailMap.put(detailId, objs);
	}
	
	public static int getCount(int countId, Details detail) {
		if(countId == 1) {
			return detail.getCount1();
		}else if (countId == 2) {
			return detail.getCount2();
		}else if (countId == 3) {
			return detail.getCount3();
		}else if (countId == 4) {
			return detail.getCount4();
		}
		return 0;
	}
	
}
